import { useEffect, useRef, useState } from "react";
import { Search as SearchIcon } from "lucide-react";
import { useSnapshot } from "valtio";
import { coreState } from "@/store/core";
import { Button } from "./ui/button";
import { Input } from "./ui/input";

export default function Search() {
  const snapCore = useSnapshot(coreState);

  const [query, setQuery] = useState("");
  const [focused, setFocused] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    // 自动聚焦搜索框
    const timer = setTimeout(() => {
      inputRef.current?.focus();
    }, 500);
    return () => clearTimeout(timer);
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!query.trim()) return;

    let searchUrl = "";
    switch (coreState.settings.searchEngine) {
      case "google":
        searchUrl = `https://www.google.com/search?q=${encodeURIComponent(query)}`;
        break;
      case "bing":
        searchUrl = `https://www.bing.com/search?q=${encodeURIComponent(query)}`;
        break;
      case "duckduckgo":
        searchUrl = `https://duckduckgo.com/?q=${encodeURIComponent(query)}`;
        break;
      case "baidu":
        searchUrl = `https://www.baidu.com/s?wd=${encodeURIComponent(query)}`;
        break;
    }

    window.location.href = searchUrl;
  };

  return (
    <div className="w-full max-w-2xl mx-auto">
      <form onSubmit={handleSubmit} className="relative">
        {/* 搜索引擎选择器 */}
        <div
          className={`mb-3 flex justify-center gap-2 transition-all duration-300 ${focused ? "opacity-100" : "opacity-80"}`}
        >
          <SearchEngineButton
            name="Baidu"
            active={snapCore.settings.searchEngine === "baidu"}
            onClick={() => coreState.setSearchEngine("baidu")}
          />
          <SearchEngineButton
            name="Bing"
            active={snapCore.settings.searchEngine === "bing"}
            onClick={() => coreState.setSearchEngine("bing")}
          />
          <SearchEngineButton
            name="Google"
            active={snapCore.settings.searchEngine === "google"}
            onClick={() => coreState.setSearchEngine("google")}
          />
          <SearchEngineButton
            name="DuckDuckGo"
            active={snapCore.settings.searchEngine === "duckduckgo"}
            onClick={() => coreState.setSearchEngine("duckduckgo")}
          />
        </div>

        {/* 搜索框 */}
        <div className="relative">
          <Input
            ref={inputRef}
            type="text"
            placeholder="Search the web..."
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            className="pl-14 pr-6 py-5 text-lg bg-background/95 backdrop-blur-md border-2 border-input/50 hover:border-input/80 focus:border-primary focus:ring-2 focus:ring-primary/20 rounded-xl transition-all duration-300 shadow-sm hover:shadow-lg focus:shadow-lg"
          />
          <SearchIcon className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-muted-foreground" />
        </div>
      </form>
    </div>
  );
}

function SearchEngineButton({ name, active, onClick }: { name: string; active: boolean; onClick: () => void }) {
  return (
    <Button
      type="button"
      variant={active ? "default" : "outline"}
      onClick={onClick}
      className={`px-4 py-2 h-auto text-sm font-medium transition-all duration-300 rounded-lg ${
        active
          ? "bg-primary text-primary-foreground shadow-md hover:bg-primary/90 hover:shadow-lg"
          : "bg-background/80 text-foreground/80 border border-input hover:bg-background hover:text-foreground hover:border-primary/30 hover:shadow-sm"
      }`}
    >
      {name}
    </Button>
  );
}
